/*
 *   Copyright 2009 Sukharev Eduard <kraplax@mail.ru>
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU Library General Public License as
 *   published by the Free Software Foundation; either version 2 or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details
 *
 *   You should have received a copy of the GNU Library General Public
 *   License along with this program; if not, write to the
 *   Free Software Foundation, Inc.,
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

#include <QtDebug>
#include <QString>
#include <QVariant>
#include <QVariantMap>
#include <QTextCodec>

#include <KIcon>
#include <plasma/dialog.h>
#include <qjson/parser.h>

#include "updateswidget.h"

UpdatesWidget::UpdatesWidget(QWidget *parent, Qt::WindowFlags, WidgetType type)// : Plasma::Frame(parent)
{
    QTextCodec *codec = QTextCodec::codecForName("UTF8");
    QTextCodec::setCodecForCStrings(codec);

    m_widgetType = type;
    init();
};

QString UpdatesWidget::colorToString(const QColor& color)
{
    static QString c("rgba(%1, %2, %3, 200)");
    return c.arg(color.red()).arg(color.green()).arg(color.blue());
};

void UpdatesWidget::init()
{
    m_colors[0] = colorToString(palette().color(QPalette::Base));
    m_colors[1] = colorToString(palette().color(QPalette::AlternateBase));
    
    m_genLayout = new QGraphicsLinearLayout(Qt::Vertical, this);  
    m_genLayout->setContentsMargins(0,0,0,0);
    m_genLayout->setSpacing(0);
    
    m_browser = new Plasma::TextBrowser();
//    m_browser->nativeWidget()->setOpenLinks(false);
    
    m_btnUpdateContent = new Plasma::PushButton();
    m_btnUpdateContent->setIcon(KIcon("view-refresh"));
    
    m_httpConnection = new QHttp("welinux.ru");

    m_genLayout->addItem(m_btnUpdateContent);
    m_genLayout->addItem(m_browser);

    connect(m_btnUpdateContent, SIGNAL(clicked()), this, SLOT(requestUpdate()));
    connect(m_httpConnection, SIGNAL(done(bool)), this, SLOT(httpDone(bool)));
};

void UpdatesWidget::setContentType(WidgetType type)
{
    m_widgetType = type;
};

void UpdatesWidget::httpDone(bool error)
{
    if(error){
        qDebug() << "An error occured while retrieving data";
        return;
    };
    updateContent();
};

void UpdatesWidget::updateContent()
{
    qDebug() << "updating coontent type" << m_widgetType;

    QJson::Parser * parser = new QJson::Parser;
    bool *status = false;
    QVariant fetchedData = parser->parse(m_buffer.data(), status);
    QString html = QString();
    
    html = "<html>\
            <body>\
            <table>";

    if(!status){
        QVariantMap dataMap = fetchedData.toMap();
        
        int id, wid, rating, strColorIndex;
        QString who, where, blog, title, user, url, itemHtml;
        strColorIndex = 3;
        foreach(QVariant item, dataMap["arr"].toList()){

            QMap<QString, QVariant> post = item.toMap();
            wid = post["wid"].toInt();
            id = post["id"].toInt();
            user = post["who"].toString();
            rating = post["rate"].toInt();
            strColorIndex += 2;
            if (wid != 0){                          //item is a comment
                where = post["where"].toString();
                blog = post["blg"].toString();
                
                itemHtml = "<tr>\
                            <td width=100% style=\"background-color:" + m_colors[(strColorIndex/2)%2] + "\"><a href=\"http://welinux.ru/user/" + who + "\">" + who + "</a> - <a href=\"http://welinux.ru/post/" + QString::number(wid) + "#cmnt" + QString::number(id) + "\">" + blog + " / " + where + "</a></td>\
                            </tr>";

            } else {                                //item is a post
                title = post["title"].toString();
                url = post["url"].toString();
                
                itemHtml = "<tr>\
                            <td width=100% style=\"background-color:" + m_colors[(strColorIndex/2)%2] + "\"><a href=\"http://welinux.ru/" + url + "\">" + who + "</a> - <a href=\"http://welinux.ru/post/" + QString::number(id) + "\">" + title + "</a></td>\
                            </tr>";
            };
            html += itemHtml;
        }
    }else{
        qDebug() << "Parsing JSon data failed!";
        return;
    };
    html += "</table>\
            </body>\
            </html>";
    m_browser->setText(html);
    m_buffer.close();
    m_buffer.setData("");
};

void UpdatesWidget::requestUpdate()
{
    qDebug() << "Requesting content update";
    m_buffer.open(QIODevice::WriteOnly);
    if(m_widgetType == Posts){
        m_httpConnection->get("/js/r_get.php?pst&date&lm=" + QString::number(m_maxFetched), &m_buffer);
    } else if(m_widgetType == Comments){
        m_httpConnection->get("/js/r_get.php?com&date&lm=" + QString::number(m_maxFetched), &m_buffer);
    } else if(m_widgetType == Mixed ){
        m_httpConnection->get("/js/r_get.php?pst&com&date&lm=" + QString::number(m_maxFetched), &m_buffer);
    };
};

void UpdatesWidget::setMaxFetched(int maxFetched)
{
    m_maxFetched = maxFetched;
};

void UpdatesWidget::reConfigure()
{
    
};
